package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.domain.CommonResult;
import com.atguigu.springcloud.domain.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired //服务发现需要在启动类上面开启服务发现功能 可以用这个对象获取一些在eureka上面的列表信息等等
    private DiscoveryClient discoveryClient;

    /*
    * 用于区分多个同名（防止服务出现问题，保证高可用性）的微服务提供者
    * */
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/discover")
    public Object discoverg(){
        //使用此方法可以获取到eureka上面的几种微服务，有些服务是集群的也只显示一次名称
        List<String> services = discoveryClient.getServices();

        for(String service:services){
            log.info("*********service:  " + service);
        }

        //通过微服务的名称获取哪一种微服务的一些相关的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("COULD-PAYMENT-SERVICE");
        for(ServiceInstance instance:instances){
            //分别是获取服务的名称和主机ip地址和端口号，和访问的路径
            log.info("****" + instance.getServiceId() + "\t"+ instance.getHost() + "\t" + instance.getPort() + "\t"+ instance.getUri());
        }
        return this.discoveryClient;
    }

    @PostMapping("/payment/addPayment")
    public CommonResult addPayment(@RequestBody Payment payment) {
        //@RequestParam(name = "page",defaultValue = "1",required = true)
        //对于post提交的非对象数据可以使用该注解，标注的传递过来的属性的名称是否必须有值，没有的话的默认值
        int i = paymentService.addPayment(payment);

        log.info("*****插入结果" + i);

        if(i > 0){
            return new CommonResult(200,"插入数据库成功，serverPort" + serverPort,i);
        }else{
            return new CommonResult(404,"插入数据库失败，serverPort" + serverPort,null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult findById(@PathVariable("id") String id) {

        Payment payment = paymentService.findById(id);

        log.info("*****插入结果" + payment);

        if(payment != null){
            return new CommonResult(200,"查询成功，serverPort" + serverPort,payment);
        }else{
            return new CommonResult(404,"查询失败： " + id + "，serverPort" + serverPort,null);
        }
    }

    @GetMapping("/payment/findAll")
    public  CommonResult findAll() {
        List<Payment> payments = paymentService.findAll();
        log.info("*****插入结果:" + payments);
        if(payments != null){
            return new CommonResult(200,"查询成功，serverPort" + serverPort,payments);
        }else{
            return new CommonResult(404,"查询失败，serverPort" + serverPort,null);
        }
    }
}